package com.spdg.ring;

import java.util.Date;

import android.app.TabActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;
import cn.wolf.http.HttpCallBack;
import cn.wolf.tools.AlertHelper;
import cn.wolf.tools.Base64Util;
import cn.wolf.tools.CommonUtils;
import cn.wolf.tools.SharedPreferencesUtil;

import com.spdg.ring.bo.CheckVersionBo;
import com.spdg.ring.bo.MenuTabsBo;
import com.spdg.ring.bo.PushBo;
import com.spdg.ring.bo.RecordBo;
import com.spdg.ring.common.Key;
import com.spdg.ring.entity.VersionEntity;
import com.spdg.ring.entity.VersionEntity.Content;
import com.spdg.ring.offline.OfflineDownloadManager;
import com.spdg.ring.resp.VersionResp;
import com.spdg.ring.service.PushService;

/**
 * <p>Title: 主界面 </p>
 * <p>Description:  </p>
 * <p>@author: caijj                </p>
 * <p>Copyright: Copyright (c) 2012    </p>
 * <p>Company: HX Co., Ltd.          </p>
 * <p>Create Time: 2012-10-6             </p>
 * <p>Update Time:                     </p>
 * <p>Updater:                         </p>
 * <p>Update Comments:                 </p>
 */
public class SplashActivity extends TabActivity {

	private TabActivity mContext;
	private RecordBo mRecordBo;
	private PushBo mPushBo;
	private CheckVersionBo mCheckVerBo;

	private View mOffline; // 关于
	
	private String versionUpdateUrl = "";	//版本升级下载地址
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.act_splash);

		mContext = this;
		initComponents();

		initData();
	}

	/**
	 * 初始化控件
	 */
	protected void initComponents() {
		mOffline = findViewById(R.id.offline);

		mOffline.setOnClickListener(new OfflineDownloadClickListener());
	}

	protected void initData() {
		new MenuTabsBo(this, getTabHost());
		mRecordBo = new RecordBo(mContext);
		mPushBo = new PushBo(mContext);
		mCheckVerBo = new CheckVersionBo(mContext, new CheckVerCallBack());

		// 注册信息
		mRecordBo.record();

		// 检查版本更新
		mCheckVerBo.checkVersion();

		// 推送
		if (!PushService.isEnable) {
			mPushBo.startAlarm();
		}
	}

	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			return exitApp();
		}
		return super.dispatchKeyEvent(event);
	}

	/**
	 * 退出应用
	 */
	protected boolean exitApp() {

		long firstTime = SharedPreferencesUtil.getLong(mContext, Key.K_EXIT_APP);
		
		Date date = new Date();
		long secondTime = date.getTime();
		if (secondTime - firstTime > 3000) { // 超过八秒钟
			Toast.makeText(mContext, R.string.exit_app, Toast.LENGTH_SHORT).show();
			SharedPreferencesUtil.setLong(mContext, Key.K_EXIT_APP, secondTime);
			return true;
		}

		SharedPreferencesUtil.setLong(mContext, Key.K_EXIT_APP, 0L); // 缓存时间清零

		sendBroadcast(new Intent(RingBaseActivity.ACTION_EXIT_APP));
		OfflineDownloadManager.getInstance().cancel(); // 退出离线下载
		
		return false;
	}

	class OfflineDownloadClickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (CommonUtils.is3g2g(mContext)) {
				String title = getString(R.string.offline_title);
				String message = getString(R.string.offline_dialog_message);
				String confirm = getString(R.string.offline_dialog_confirm);
				String cancel = getString(R.string.offline_dialog_cancel);
				AlertHelper.showConfirm(mContext, title, message, confirm, cancel,
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog, int which) {
								offlineDownload();
							}
						}, null);
				return;
			}
			offlineDownload();
		}
	}

	private void offlineDownload() {
		OfflineDownloadManager.getInstance().start(mContext);
	}

	class CheckVerCallBack implements HttpCallBack<VersionResp> {

		@Override
		public void call(VersionResp response) {
			try { // 捕获base64解密异常
				if (response.isSuccess()) {

					VersionEntity entity = response.getEntity();
					Content content = entity.getContent();
					String update = Base64Util.decode2String(content.getUpdate());
					versionUpdateUrl = Base64Util.decode2String(content.getUrl());

					if (CheckVersionBo.VERSION_UPDATE.equals(update)) {
						String tip = getString(R.string.check_version_new);
						AlertHelper.showConfirm(mContext, tip, new OnConfirmClickListener(), null);
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		@Override
		public void progress(Object... obj) {
		}
		
		@Override
		public void onNetWorkError() {
		}
	}

	// 升级版本
	class OnConfirmClickListener implements android.content.DialogInterface.OnClickListener {

		@Override
		public void onClick(DialogInterface dialog, int which) {
			// 调用本地浏览器进行版本下载
			Uri uri = Uri.parse(versionUpdateUrl);
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			startActivity(intent);
		}
	}

	/**
	 * 注册退出应用广播,默认注册
	 * 发送动作为action_exit_app的广播，可销毁所有Activity <br/>
	 * 不想当前activity被销毁，可覆盖该方法
	 */
	private BroadcastReceiver eixtBroadcastReceiver;

	protected void registerExitReceiver() {
		eixtBroadcastReceiver = new ExitBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(RingBaseActivity.ACTION_EXIT_APP);
		registerReceiver(eixtBroadcastReceiver, filter);
	}

	// 接收退出广播
	private class ExitBroadcastReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			finish();
		}
	}
}
